package com.typingtutor.dto;

import com.typingtutor.db.DatabaseManager;
import com.typingtutor.model.RandomRule;
import org.apache.commons.compress.utils.Lists;

import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class RandomRuleDAO extends BaseDAO {
    private static volatile RandomRuleDAO INSTANCE;
    private RandomRuleDAO() {
        // 私有构造函数，防止实例化
    }
    public static RandomRuleDAO getInstance() {
        if (INSTANCE == null) {
            synchronized (RandomRuleDAO.class) {
                if (INSTANCE == null) {
                    INSTANCE = new RandomRuleDAO();
                }
            }
        }
        return INSTANCE;
    }
    public void enableRandomRule(String randomRuleId) {
        String selectRandomRule = "SELECT * FROM folder_random_rules WHERE id = ?";
        String updateRandomRule = "UPDATE folder_random_rules SET default_enabled = 0 WHERE folder_id = ?";
        String updateRandomRuleEnabled = "UPDATE folder_random_rules SET default_enabled = 1 WHERE id = ?";
        Connection connection = null;
        try {
            connection = DatabaseManager.getConnection();
            connection.setAutoCommit(false);
            PreparedStatement pstmt = connection.prepareStatement(selectRandomRule);
            pstmt.setString(1, randomRuleId);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String folderId = rs.getString("folder_id");
                PreparedStatement pstmt1 = connection.prepareStatement(updateRandomRule);
                pstmt1.setString(1, folderId);
                pstmt1.executeUpdate();
            }
            PreparedStatement pstmt2 = connection.prepareStatement(updateRandomRuleEnabled);
            pstmt2.setString(1, randomRuleId);
            pstmt2.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            if (connection != null) {
                try {
                    connection.rollback();
                    System.out.println("事务回滚！");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            JOptionPane.showMessageDialog(null, "启用失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        }
    }

    public void updateRandomRuleById(String randomRuleId, String updateField, String fieldValue) {
        String updateRandomRule = "UPDATE folder_random_rules SET " + updateField + " = ? WHERE id = ?;";
        try (Connection connection = DatabaseManager.getConnection()) {
            PreparedStatement ptsmt = connection.prepareStatement(updateRandomRule);
            ptsmt.setString(1, fieldValue);
            ptsmt.setString(2, randomRuleId);
            ptsmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<RandomRule> findById(String randomRuleId) {
        String selectSql = "SELECT * FROM folder_random_rules WHERE id = ?;";
        try (Connection connection = DatabaseManager.getConnection()) {
            PreparedStatement pstmt = connection.prepareStatement(selectSql);
            pstmt.setString(1, randomRuleId);
            ResultSet rs = pstmt.executeQuery();
            List<RandomRule> randomRules = Lists.newArrayList();
            while (rs.next()) {
                randomRules.add(new RandomRule(rs.getString("id")
                , rs.getString("random_range")
                , rs.getString("operator_str")
                , rs.getString("math_field")
                , rs.getBoolean("default_enabled")
                , rs.getString("folder_id")));
            }
            return randomRules;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }

    public List<RandomRule> findEnabledRandomByFolderId(String folderId) {
        String selectSql = "SELECT * FROM folder_random_rules WHERE folder_id = ? AND default_enabled = true;";
        try (Connection connection = DatabaseManager.getConnection()) {
            PreparedStatement pstmt = connection.prepareStatement(selectSql);
            pstmt.setString(1, folderId);
            ResultSet rs = pstmt.executeQuery();
            List<RandomRule> randomRules = Lists.newArrayList();
            while (rs.next()) {
                randomRules.add(new RandomRule(rs.getString("id")
                , rs.getString("random_range")
                , rs.getString("operator_str")
                , rs.getString("math_field")
                , rs.getBoolean("default_enabled")
                , rs.getString("folder_id")));
            }
            return randomRules;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }

    public void deleteById(String randomRuleId) {
        String deleteSql = "DELETE FROM folder_random_rules WHERE id = ?;";
        try (Connection connection = DatabaseManager.getConnection()) {
            PreparedStatement pstmt = connection.prepareStatement(deleteSql);
            pstmt.setString(1, randomRuleId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
